<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :sm="24" :lg="24">
        <div class="bottom-table">
          <div class="table-header">
            <div class="table-title" v-if="weekTitle && weekTitle !== ''">{{ weekTitle }}</div>
            <div class="table-title" v-else>xxxx-xx-xx至xxxx-xx-xx招标安排</div>
            <div class="btn-groups">
              <el-button type="primary" plain size="mini" @click="handleAdd" v-hasPermi="['system:plan:add']">新 增</el-button>
              <el-button type="primary" size="mini" plain @click="handleSwitch(-1)">上一周</el-button>
              <el-button type="primary" size="mini" plain @click="handleSwitch(1)">下一周</el-button>
              <el-button type="primary" size="mini" plain @click="handleSwitch(0)">本 周</el-button>
              <el-button type="warning" size="mini" plain @click="dayinopen = true">打 印</el-button>
            </div>
          </div>
          <div class="print-scale">
            <el-table class="print-table" :data="tableData" :span-method="objectSpanMethod" v-loading="loading" :row-class-name="tableRowClassName" :header-cell-style="rowClass" border style="width: 100%; margin-top: 20px">
              <el-table-column label="日期" align="center">
                <el-table-column prop="content" header-align="center" class-name="data-time" width="40" />
                <el-table-column prop="planTime" header-align="center" class-name="data-time" width="40" />
              </el-table-column>
              <el-table-column v-for="(item, index) in header" class-name	="table-content-cell" :key="index" header-align="center" align="left" :prop="item.prop" :label="`${item.weekname}（${item.weekTime}）`">
                <template slot-scope="scope">
                  <div :style="{color: form.deptId === sonItem.deptId ? '#F56C6C' : '#606266', cursor: form.deptId === sonItem.deptId ? 'pointer' : ''}"
                    v-for="(sonItem, sonIndex) in scope.row[item.prop]"
                    @dblclick="cellDbClick(sonItem)"
                    :key="sonIndex">
                    {{ sonIndex + 1 }}、{{ sonItem.planContent }} - {{ selectDictLabel(dict.type.plan_bidmethods, sonItem.bidmethod) }} - {{ sonItem.deptName }} - {{ selectDictLabel(dict.type.plan_area, sonItem.planArea) }}（{{ sonItem.planPrice }}万元） 
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改开标计划对话框 -->
    <el-dialog :title="title" v-dialogDrag :visible.sync="open" width="60%" :close-on-click-modal="false" >
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="招标部门" prop="deptName">
              <el-input v-model="form.deptName" disabled placeholder="请选择招标部门" />
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="项目选择" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请选择项目" @focus="projectFocus" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="组织方式" prop="bidmethod">
              <el-select v-model="form.bidmethod" placeholder="请选择组织方式">
                <el-option
                  v-for="dict in dict.type.plan_bidmethods"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="招标类别" prop="bidcategory">
              <el-input :value="selectDictLabel(dict.type.sys_bidcategory, form.bidcategory)" disabled placeholder="请选择招标部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="招标日期" prop="planDate">
              <el-select v-model="form.planDate" placeholder="请选择招标日期" @change="getPlanAreaOptions">
                <el-option
                  v-for="(item, index) in planDateOptions"
                  :key="index"
                  :label="`${item.weekname}（${item.weekTime}）`"
                  :value="item.weekTime">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="招标时间" prop="planTime">
              <el-select v-model="form.planTime" placeholder="请选择招标时间" @change="getPlanAreaOptions">
                <el-option
                  v-for="dict in dict.type.plan_time"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="招标会议室" prop="planArea">
              <el-select v-model="form.planArea" placeholder="请选择招标会议室">
                <el-option
                  v-for="item in planAreaOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item label="预计招标值" prop="planPrice">
              <el-input class="pirce" v-model="form.planPrice" placeholder="请输入预计招标值" /> 万元
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-form-item label="招标内容" prop="planContent">
              <el-input v-model="form.planContent" placeholder="请输入招标内容" type="textarea" :rows="5" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="handleDelete" v-hasPermi="['system:plan:remove']" v-if="this.form.id">删 除</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 项目弹框开始 -->
      <el-dialog title="选择项目" :visible.sync="project.open" width="48%" :close-on-click-modal="false" >
        <el-form class="projectClassName" :model="project.queryParams" ref="projectQueryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="项目编号" prop="pid">
            <el-input v-model="project.queryParams.pid" placeholder="请输入项目编号" clearable @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
          <el-form-item label="项目名称" prop="pname">
            <el-input v-model="project.queryParams.pname" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" @clear="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="重置" placement="top">
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"></el-button>
            </el-tooltip>
          </el-form-item>
        </el-form>
        <el-table ref="objectTable"
          v-loading="project.loading"
          stripe
          border
          class="no-multiple"
          max-height="540px"
          :data="project.list"
          :default-sort="defaultSort"
          highlight-current-row
          :row-key="getRowKey"
          @selection-change="handleSelectionChange" 
          @select="selectTable">
          <el-table-column
            label="项目编号"
            type="selection"
            align="center"
            reserve-selection
            width="55">
          </el-table-column>
          <el-table-column label="项目编号" fixed align="center" prop="pid" show-overflow-tooltip width="120">
            <template slot-scope="scope">
              <span @dblclick="copyText(scope.row.pid)">{{ scope.row.pid }}</span>
            </template>
          </el-table-column>
          <el-table-column label="项目名称" align="center" prop="pname" show-overflow-tooltip>
            <template slot-scope="scope">
              <span @dblclick="copyText(scope.row.pname)">{{ scope.row.pname }}</span>
            </template>
          </el-table-column>
          <el-table-column label="委托单位" align="center" prop="clientName" show-overflow-tooltip width="160"/>
          <el-table-column label="审批状态" align="center" show-overflow-tooltip prop="status" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 0 || scope.row.status === 1 ? '' : (scope.row.status === 3 ? 'success' : 'danger')">{{ selectDictLabel(dict.type.sys_approval_status, scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="审批时间" align="center" prop="agreeTime" width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.agreeTime) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="project.total>0"
          :total="project.total"
          :page.sync="project.queryParams.pageNum"
          :limit.sync="project.queryParams.pageSize"
          @pagination="getProjectList"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="projectSubmitForm">确 定</el-button>
          <el-button @click="projectCancel">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 项目弹框结束 -->


   





    <!-- 打印内容 -->
    <el-dialog :visible.sync="dayinopen" width="64%" class="dayin-dialog" title="打印内容确认">
      <div id="mytable1" class="previewContent">
        <div class="table-title" v-if="weekTitle && weekTitle !== ''">{{ weekTitle }}</div>
        <table class="previewTable" border="1">
          <tr>
            <th colspan="2">日期</th>
            <th v-for="(item, index) in header">{{ item.weekname }}（{{ item.weekTime }}）</th>
          </tr>
          <tr v-for="(item, index) in tableData">
            <td class="content" rowspan="2" v-if="index === 0">招标内容</td>
            <td class="content" >{{ item.planTime }}</td>
            <td v-for="weekItem in weekList" class="table-content-td">
              <div class="table-content">
                <div class="table-content-br" v-for="(sonItem, sonIndex) in item[weekItem]">{{ sonIndex + 1 }}、{{ sonItem.planContent }}-{{ sonItem.deptName }}-{{ selectDictLabel(dict.type.plan_area, sonItem.planArea) }}-（{{ sonItem.planPrice }}万元）</div>
              </div>
            </td>
          </tr>
        </table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlePrint">打 印</el-button>
        <el-button @click="dayinopen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject } from "@/api/projectManage/negoApplication"
import { listPlan, getPlan, delPlan, addPlan, updatePlan, getPlanAreaOptions } from "@/api/projectManage/plan";
import printJS from 'print-js'
import { mapGetters } from "vuex"
export default {
  dicts: ['plan_time', 'plan_area', 'sys_approval_status', 'sys_bidcategory', 'plan_bidmethods'],
  data() {
    return {
      // 遮罩层
      loading: true,
      title: '',
      open: false,
      planDateOptions: [],
      planAreaOptions: [],
      planDetail: {},
      form: {},
      rules: {
        planDate: [
          { required: true, message: "招标日期不能为空", trigger: "blur" }
        ],
        planTime: [
          { required: true, message: "招标时间不能为空", trigger: "blur" }
        ],
        planArea: [
          { required: true, message: "招标会议室不能为空", trigger: "blur" }
        ],
        planContent: [
          { required: true, message: "招标内容不能为空", trigger: "blur" }
        ],
        planPrice: [
          { required: true, message: "预计招标值不能为空", trigger: "blur" }
        ],
        planContent: [
          { required: true, message: "招标内容不能为空", trigger: "blur" }
        ],
        projectName: [
          { required: true, message: "项目选择不能为空", trigger: "change" }
        ],
        bidmethod: [
          { required: true, message: "组织方式不能为空", trigger: "change" }
        ]
      },
      tableData: [],
      header: [],
      queryParams: {
        weeks: 0
      },
      weekTitle: '',
      printOptions: {
        id: 'mytable1',
        preview: true,
        excludeStyles: ['display']
      },
      weekList: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
      dayinopen: false,


      // 项目内容
      project: {
        open: false,
        loading: false,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          pname: null,
          pid: null,
          deptName: null,
          bidcategorys: null
        },
        // 存储项目选择视图
        checkProjectId: null,
        checkProjectName: null,
        // 项目列表
        list: [],
        total: 0
      },
      defaultSort: {prop: 'agreeTime', order: 'descending'},

    }
  },
  computed: {
    ...mapGetters(['roles', 'userInfo'])
  },
  created() {
    if (this.roles) {
      this.form.deptId = this.userInfo.deptId
      this.form.deptName = this.userInfo.dept.deptName
    }
    this.getList()
  },
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 合并列
      if (rowIndex === 0 && columnIndex === 0) {
        return {
          rowspan: 2,
          colspan: 1
        }
      } else if (rowIndex === 1 && columnIndex === 0) {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    },
    rowClass({ row, column,rowIndex,columnIndex}) {
      if(rowIndex===0 && columnIndex===0) {
        this.$nextTick(()=> {
          if(document.getElementsByClassName(column.id).length!==0) {
            document.getElementsByClassName(column.id)[0].setAttribute('rowSpan',2);
            return false
          }
        })
      }
      if(rowIndex===1 && (columnIndex===0 || columnIndex===1)) {
        return {display:'none'}
      }

    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 0) {
        return 'primary-row';
      } else if (rowIndex === 1) {
        return 'success-row';
      }
      return '';
    },
    // 获取会议室
    async getPlanAreaOptions() {
      const queryParams = {
        planDate: this.form.planDate,
        planTime: this.form.planTime,
      }
      const res = await getPlanAreaOptions(queryParams)
      console.log(res)
      
      if (res.code == 200) {
        this.planAreaOptions = res.data
      } else {
        this.planAreaOptions = []
      }
      

    },
    // 上一周下一周切换
    handleSwitch(num) {
      if (num === 0) {
        this.queryParams.weeks = num
      } else {
        this.queryParams.weeks += num
      }
      this.getList()
    },
    // 获取招标计划
    getList() {
      this.loading = true
      this.planDateOptions = []
      listPlan(this.queryParams).then(response => {
        response.data.weekHeader.forEach(item => {
          this.planDateOptions.push(item)
        })
        this.weekTitle = response.data.weekTitle
        this.header = response.data.weekHeader
        response.data.content.forEach(item => {
          item['content'] = '招标内容'
        })
        this.tableData = response.data.content
        this.loading = false
      })
    },
    // 单元格双击击
    cellDbClick(item) {
      if (item.deptId !== this.form.deptId) return
      // this.reset()
      this.title = "修改开标计划"
      this.form = item
      this.getPlanAreaOptions()
      this.open = true
    },
    // 新增
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加开标计划"
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        planDate: null,
        planTime: null,
        planArea: null,
        planContent: null,
        planPrice: null,
        deptName: null,
        projectId: null,
        projectName: null,
        bidcategory: null,
        bidmethod: null,
        deptId: this.userInfo.deptId,
        deptName: this.userInfo.dept.deptName
      };
      this.resetForm("form");
    },
     /** 删除按钮操作 */
     handleDelete() {
      const ids = this.form.id;
      this.$modal.confirm('是否确认删除开标计划编号为"' + ids + '"的数据项？').then(function() {
        return delPlan(ids);
      }).then(() => {
        this.getList()
        this.open = false
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {});
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("计划修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("计划新增成功")
              this.open = false
              this.getList()
            });
          }
        }
      })
    },
    cancel() {
      this.open = false
    },
    handlePrint () {
      const printCss = `
        #mytable1 {
          font-family: Arial, sans-serif;
        }
        .table-content {
          text-align: left;
          min-height: 322px;
        }
        .content {
          width: 50px;
          line-height: 1.6;
        }
        td {
          width: 13.6%;
          padding: 4px;
          font-size: 12px;
          line-height: 1.6;
        }
        .table-content-td {
          vertical-align: top;
        }
        th {
          height: 30px;
          font-size: 12px;
        }
        tbody {
          text-align: center;
        }
        table {
          width: 100%;
          border-collapse: collapse;
          text-align: center;
          margin-top: 60px;
          overflow: auto;
        }
        .table-title {
          font-size: 14px;
          font-weight: bold;
          padding: 10px 0 8px 0;
          text-align: center;
          position: absolute;
          top: 20px;
          left: 50%;
          transform: translate(-50%, 0%);
        }
      `
      printJS({
        printable: 'mytable1', // 标签元素id
        type: 'html',
        scanStyles: false,
        style: `@page { size:auto; position: relative; margin-top: 0px; margin-left:16px; margin-right: 24px; }` + printCss,
      });
    },


    // 项目选择
    projectFocus() {
      this.getProjectList()
      this.project.open = true
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.project.queryParams.pageNum = 1;
      this.getProjectList()
    },
    /** 搜索重置 */
    resetQuery() {
      this.resetForm("projectQueryForm")
      this.handleQuery()
    },
    /** 获取项目列表 */
    getProjectList() {
      this.project.loading = true
      if (this.roles && (this.roles.indexOf('zb_b') > -1 || this.roles.indexOf('zb_f') > -1)) {
        // 招标部
        this.project.queryParams.deptId = this.userInfo.deptId
        this.project.queryParams.bidcategorys = null
      } else if (this.roles.indexOf('fg_gf') > -1) {
        // 分管工程服务
        this.project.queryParams.bidcategorys = [0, 2]
        this.project.queryParams.deptId = null
      } else if (this.roles.indexOf('fg_h') > -1) {
        // 分管货物
        this.project.queryParams.bidcategorys = [1]
        this.project.queryParams.deptId = null
      } else {
        this.project.queryParams.deptId = null
        this.project.queryParams.bidcategorys = null
      }
      listProject(this.project.queryParams).then(response => {
        this.project.list = response.rows
        this.project.total = response.total
        this.project.loading = false
        if (this.form.projectId) {
          this.project.list.forEach(item => {
            if (this.form.projectId === item.id) {
              this.form.projectName = item.pname
              this.$refs.objectTable.toggleRowSelection(item)
            }
          })
        }

      })
    },
    async copyText(textToCopy) {
      // navigator clipboard 需要https等安全上下文
      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        navigator.clipboard.writeText(textToCopy).then(() => {
          this.$modal.msgSuccess('复制成功！')
        })
      } else {
        // 创建text area
        let textArea = document.createElement("textarea");
        textArea.value = textToCopy;
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = "absolute";
        textArea.style.opacity = '0';
        textArea.style.left = "-999999px";
        textArea.style.top = "-999999px";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        let res = new Promise((res, rej) => {
          res(() => {
            document.execCommand('copy')
            textArea.remove();
          })
          rej(false)
        })
        res.then(res => {
          res();
          this.$modal.msgSuccess('复制成功！')
        }).catch(error => {
          this.$modal.msgError('复制失败！')
        })
      }
    },
    getRowKey(row) {
      return row.id
    },
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.objectTable.clearSelection()
        this.$refs.objectTable.toggleRowSelection(val.pop())
      }
    },
    selectTable(selection, row) {
      this.project.checkProjectId = row.id
      this.project.checkProjectName = row.pname
      this.project.checkProjectBidcategory = row.bidcategory
    },

    projectSubmitForm() {
      this.form.projectId = this.project.checkProjectId
      this.form.projectName = this.project.checkProjectName
      this.form.bidcategory = this.project.checkProjectBidcategory
      this.projectCancel()
    },
    projectCancel() {
      // 取消选择
      this.$refs.objectTable.clearSelection()
      // 清空数据
      this.project.checkProjectId = null
      this.project.checkProjectName = null
      this.project.checkProjectBidcategory = null
      // 关闭弹框
      this.project.open = false
    },


  }
}
</script>

<style lang="scss" scoped>
::v-deep .bottom-table {
  .table-header {
    .table-title {
      font-size: 18px;
      font-weight: bold;
      width: 100%;
      display: flex;
      justify-content: center;
    }
    .btn-groups {
      width: 100%;
      display: flex;
      justify-content: flex-end;
    }
  }
  .el-table {
    .el-table__body-wrapper {
      .table-content-cell {
        vertical-align: top;
      }
      .cell {
        user-select: none;
        min-height: 300px;
      }
    }
    .data-time {
      .cell {
        display: flex;
        align-items: center;
      }
    }
    tbody tr:hover > td {
      background-color: unset !important;
    }
    tbody tr > td:hover {
      background-color: rgba(81, 90, 110, 0.06) !important;
    }
  }
}
::v-deep .el-dialog{
  .el-date-editor, .el-input, .el-select {
    width: 100%;
  }
  .el-pagination {
    .el-date-editor, .el-input, .el-select {
      width: auto;
    }
  }
  .el-dialog__body {
    padding: 30px 10px 30px 30px;
  }
  .el-form-item__label {
    max-width: 100px; /* 你可以根据需要调整这个值 */
    white-space: nowrap; /* 防止文字换行 */
    overflow: hidden; /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 文字溢出时显示省略号 */
  }
  .is-disabled{
    .el-textarea__inner, .el-input__inner {
      color: #333333;
    }
    .el-radio__label {
      color: #333333;
    }
    .el-radio__inner {
      border-color: #333333;
      &::after {
        background: #333333;
      }
    }
  }
  .pirce {
    width: 92%;
  }
}

::v-deep .dayin-dialog {
  .el-dialog__body {
    padding-top: 0 !important;
  }
}
.previewContent {
  .table-title {
    font-size: 16px;
    font-weight: bold;
    padding: 10px 0;
    width: 100%;
    height: 60px;
    text-align: center;
    position: relative;
    .el-button {
      position: absolute;
      right: 0;
    }
  }
  .previewTable {
    width: 100%;
    border-collapse: collapse;
    th, td {
      text-align: left;
      padding: 5px 10px;
      line-height: 1.5;
      font-size: 12px !important;
    }
    .table-content-td {
      vertical-align: top;
    }
    td {
      width: 13.6%;
    }
    th {
      text-align: center;
      height: 40px;
    }
    .content {
      padding: 0 10px;
      width: 50px;
    }
    .table-content {
      min-height: 260px;
    }
  }
}

.projectClassName {
  .el-input {
    width: 230px !important;
  }
}

::v-deep .no-multiple {
  // 隐藏多选
  .el-table__fixed-header-wrapper .el-checkbox {
    display: none;
  }
}
::v-deep .is-disabled {
  .el-input__inner {
    background-color: #ffffff;
  }
  
}
</style>
